<template>
  <div class="departments-container">
    <div class="page-header">
      <h2 class="page-title">个人信息</h2>
    </div>

    <el-row :gutter="20">
      <!-- 左侧个人信息卡片 -->
      <el-col :span="8">
        <el-card class="profile-card">
          <div class="avatar-container">
            <el-avatar :size="100" :src="avatarUrl">
              {{ userInfo.username ? userInfo.username.charAt(0).toUpperCase() : 'U' }}
            </el-avatar>
            <el-upload
              class="avatar-uploader"
              action="#"
              :http-request="uploadAvatar"
              :show-file-list="false"
              accept="image/*"
            >
              <el-button size="small" type="primary" class="change-avatar-btn">
                更换头像
              </el-button>
            </el-upload>
          </div>
          
          <div class="user-info">
            <h3>{{ userInfo.name || userInfo.username }}</h3>
          </div>
          
          <div class="user-details">
            <!-- 用户信息栅格布局 -->
            <div class="info-row">
              <span class="info-label">用户角色：</span>
              <div class="info-value">
                <el-tag size="small" effect="plain">{{ getRoleName }}</el-tag>
              </div>
            </div>
            
            <div class="info-row">
              <span class="info-label">所属部门：</span>
              <div class="info-value">
                <el-tooltip 
                  v-if="userInfo.department_path && userInfo.department_path.length > 25"
                  :content="userInfo.department_path || '未分配部门'" 
                  placement="top"
                >
                  <span>{{ formatDepartmentPath(userInfo.department_path) }}</span>
                </el-tooltip>
                <span v-else>{{ formatDepartmentPath(userInfo.department_path) }}</span>
              </div>
            </div>
            
            <div class="info-row">
              <span class="info-label">账号状态：</span>
              <div class="info-value">
                <el-tag :type="userInfo.status === '启用' ? 'success' : 'danger'" size="small">
                  {{ userInfo.status || '未知' }}
                </el-tag>
              </div>
            </div>
            
            <div class="info-row">
              <span class="info-label">注册时间：</span>
              <div class="info-value">{{ userInfo.created_at ? formatDateTime(userInfo.created_at) : '未知' }}</div>
            </div>
            
            <div class="info-row">
              <span class="info-label">更新时间：</span>
              <div class="info-value">{{ userInfo.updated_at ? formatDate(userInfo.updated_at) : '未知' }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 右侧信息编辑表单 -->
      <el-col :span="16">
        <el-card class="edit-card">
          <template #header>
            <div class="card-header">
              <span>编辑个人信息</span>
            </div>
          </template>
          
          <el-form 
            ref="formRef" 
            :model="form" 
            :rules="rules" 
            label-width="100px"
            label-position="left"
          >
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" disabled />
            </el-form-item>
            
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
            
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号码" />
            </el-form-item>
            
            <el-form-item label="性别">
              <el-radio-group v-model="form.gender">
                <el-radio value="男">男</el-radio>
                <el-radio value="女">女</el-radio>
                <el-radio value="保密">保密</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="个人简介" prop="bio">
              <el-input 
                v-model="form.bio" 
                type="textarea" 
                :rows="4" 
                placeholder="请输入个人简介"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="submitForm" :loading="loading">保存修改</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        

      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getUserProfile, updateUserProfile, uploadUserAvatar } from '@/api/user'
import { getApiBaseUrl } from '@/utils/config'
import { formatDateTime, formatAvatarUrl } from '@/utils/format'

const userStore = useUserStore()
const defaultAvatar = ref('')

// 用户信息
const userInfo = computed(() => userStore.getUserInfo)
const loading = ref(false)
const formRef = ref(null)

// 获取头像URL（现在支持base64）
const avatarUrl = computed(() => {
  return formatAvatarUrl(userInfo.value.avatar, defaultAvatar.value);
})

// 获取角色名称
const getRoleName = computed(() => {
  if (userInfo.value.roles && userInfo.value.roles.length > 0) {
    return userInfo.value.roles[0].name;
  }
  return '未知角色';
})

// 格式化部门路径，处理过长文本
const formatDepartmentPath = (path) => {
  if (!path) return '未分配部门';
  // 如果路径太长，截断并添加省略号（在tooltip中会显示完整路径）
  if (path.length > 25) {
    return path.substring(0, 22) + '...';
  }
  return path;
}

// 表单数据
const form = reactive({
  username: '',
  name: '',
  email: '',
  phone: '',
  gender: '保密',
  bio: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  bio: [
    { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  loading.value = true
  try {
    // 先尝试从用户存储中获取信息
    if (Object.keys(userInfo.value).length > 0) {
      // 填充表单
      form.username = userInfo.value.username || '';
      form.name = userInfo.value.name || '';
      form.email = userInfo.value.email || '';
      form.phone = userInfo.value.phone || '';
      form.gender = userInfo.value.gender || '保密';
      form.bio = userInfo.value.bio || '';
    } else {
      // 如果用户存储中没有信息，则调用API获取
      await userStore.fetchUserInfo()
      
      // 重新填充表单
      form.username = userInfo.value.username || '';
      form.name = userInfo.value.name || '';
      form.email = userInfo.value.email || '';
      form.phone = userInfo.value.phone || '';
      form.gender = userInfo.value.gender || '保密';
      form.bio = userInfo.value.bio || '';
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 发送所有支持的字段
        const userData = {
          name: form.name,
          email: form.email,
          phone: form.phone,
          gender: form.gender,
          bio: form.bio
        }
        
        // 调用用户存储中的方法更新用户信息
        const success = await userStore.updateUserInfo(userData)
        
        if (success) {
          ElMessage.success('个人信息更新成功')
        } else {
          ElMessage.error('个人信息更新失败')
        }
      } catch (error) {
        console.error('更新用户信息失败:', error)
        ElMessage.error('更新用户信息失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    
    // 重新填充表单
    form.username = userInfo.value.username || '';
    form.name = userInfo.value.name || '';
    form.email = userInfo.value.email || '';
    form.phone = userInfo.value.phone || '';
    form.gender = userInfo.value.gender || '保密';
    form.bio = userInfo.value.bio || '';
  }
}



// 上传头像
const uploadAvatar = async (options) => {
  const file = options.file
  
  // 验证文件类型和大小
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return
  }
  
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return
  }
  
  try {
    // 创建FormData对象
    const formData = new FormData()
    
    // 保留原始文件名，这样后端可以使用它作为文件名的一部分
    formData.append('file', file, file.name)
    
    try {
      // 调用API上传头像
      const response = await uploadUserAvatar(formData)
      console.log('头像上传响应:', response)
      
      if (response && response.data && response.data.avatar) {
        console.log('服务器返回的头像数据:', response.data.avatar.substring(0, 50) + '...')
        
        // 更新用户存储中的头像
        userStore.updateAvatar(response.data.avatar)
        ElMessage.success(response.message || '头像上传成功')
        
        // 强制刷新用户信息
        await userStore.fetchUserInfo()
      } else {
        console.error('服务器响应中没有头像数据:', response)
        ElMessage.warning('头像上传成功，但获取数据失败')
      }
    } catch (error) {
      console.error('API请求失败，使用模拟上传', error)
      // 模拟上传 - 在客户端进行base64编码
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        // 更新头像
        userStore.updateAvatar(reader.result)
        ElMessage.success('头像上传成功')
      }
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('上传头像失败')
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return formatDateTime(dateStr, false)
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;
  margin: 0;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.el-row {
  display: flex;
}

.el-col {
  display: flex;
  flex-direction: column;
}

.profile-card, .edit-card {
  margin-bottom: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}
  
.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
  
  .el-avatar {
    margin-bottom: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  }
  
  .change-avatar-btn {
    margin-top: 10px;
  }
}
  
.user-info {
  text-align: center;
  margin-bottom: 20px;
  
  h3 {
    margin: 0 0 20px;
    font-size: 18px;
    font-weight: 600;
  }
}

.user-details {
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
  margin-top: auto;
  
  .info-row {
    display: flex;
    margin-bottom: 12px;
    align-items: center;
    font-size: 14px;
    line-height: 1.5;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .info-label {
      width: 85px;
      text-align: right;
      color: #606266;
      padding-right: 12px;
      font-weight: normal;
    }
    
    .info-value {
      flex: 1;
      color: #303133;
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  span {
    font-size: 16px;
    font-weight: 500;
  }
}
</style> 